#!/usr/bin/env bash
# Summary: List all Java versions available to jenv
# Usage: jenv versions [--bare] [--verbose]
#
# Lists all Java versions found in `$JENV_ROOT/versions/*'.

set -e
[ -n "$JENV_DEBUG" ] && set -x
verbose=false

if [ "$1" = "--bare" ]; then
  hit_prefix=""
  miss_prefix=""
  current_version=""
  include_system=""
else
  hit_prefix="* "
  miss_prefix="  "
  current_version="$(jenv-version-name || true)"
  include_system="1"
fi
if [ "$1" = "--verbose" ]; then
  verbose=true
fi

resolvepath() {
  local cwd="$(pwd)" 
  cd $1
  echo "$(pwd -P)"
  cd "$cwd"
}


print_version() {


  if [ "$1" == "$current_version" ]; then
    echo "${hit_prefix}$(jenv-version 2>/dev/null)"
    if $verbose ; then
      local realPath="$(resolvepath $2)"
     echo "         $2"
     echo "         --> $realPath"
     echo ""
    fi
  else
    echo "${miss_prefix}$1"
    if $verbose ; then
            local realPath="$(resolvepath $2)"

      echo "         $2"
     echo "         --> $realPath"
     echo ""
    fi
  fi
}

# Include "system" in the non-bare output, if it exists
if [ -n "$include_system" ] && JENV_VERSION=system jenv-which java >/dev/null 2>&1; then
  print_version system
fi

for path in "${JENV_ROOT}/versions/"*; do
  if [ -d "$path" ]; then
    #print_version "${path##*/}"
    print_version "${path##*/}" "$path"
  fi
done
